<?php namespace App\Services;

use App\Models\ItemImage;
use App\Http\Requests\ItemImageRequest;
use Auth;
use File;

class ItemImageService
{
    //相对public目录
    private $path = '/static/uploads/itemImages/';

    public function create(ItemImageRequest $itemImageRequest)
    {
        $file = $itemImageRequest->file('image');
        $name = $file->getClientOriginalName();
        $file_path = $this->getPath();
        $file_name = md5($name . time()) . '.' . $file->getClientOriginalExtension();
        $file->move($file_path, $file_name);
        return ItemImage::create([
            'user_id' => Auth::user()->id,
            'name' => $name,
            'url' => $this->path . date('Y-m-d') . '/' . $file_name,
            'file_path' => $file_path,
            'file_name' => $file_name,
        ]);
    }

    public function saveImages(array $item_images, $item_id)
    {
        $old = [];
        $itemImages = ItemImage::where(['user_id' => Auth::user()->id, 'item_id' => 0])->get();
        foreach ($itemImages as $itemImage) {
            if ((isset($old[$itemImage->name]) && $old[$itemImage->name]) || !in_array($itemImage->name, $item_images)) {
                $file = $itemImage->file_path . '/' . $itemImage->file_name;
                File::delete($file);
                $itemImage->delete();
            } else {
                $old[$itemImage->name] = true;
                $itemImage->item_id = $item_id;
                $itemImage->save();
            }
        }
    }

    private function getPath()
    {
        $path = dirname(app_path()) . '/public' . $this->path . date('Y-m-d');
        $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path);
        if (!File::isDirectory($path)) {
            File::makeDirectory($path);
        }
        return $path;
    }

}